package org.piggy.client.rpc.proxy;

import com.alibaba.fastjson2.JSONObject;
import org.piggy.client.rpc.client.NettyClient;
import org.piggy.client.rpc.utils.ToolUtil;
import org.piggy.common.async.RequestFuture;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JdkProxy implements InvocationHandler {

    private final Field target;

    public JdkProxy(Field target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        long id = ToolUtil.aid.incrementAndGet();
        RequestFuture request = new RequestFuture(id);
        request.setPath(target.getType().getName() + "." + method.getName());
        request.setParam(args);
        ToolUtil.futures.put(id, request);
        Object obj = NettyClient.sendRequest(request);
        String json = JSONObject.toJSONString(obj);
        Class<?> returnType = method.getReturnType();
        return JSONObject.parseObject(json, returnType);
    }

}
